//
//  PersonShowVC.m
//  xpkc
//
//  Created by TopSage OS X on 15/11/27.
//  Copyright © 2015年 TopSage. All rights reserved.
//

#import "PersonShowVC.h"
#import "ChangePassWordVC.h"
#import "UserMessage.h"
#import "UIImageView+AFNetworking.h"
@interface PersonShowVC ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong) UIImageView * imageView;
@property (nonatomic,strong) UIView * shaowView;

@property (nonatomic,strong) NSMutableArray * dataArr;
@end

@implementation PersonShowVC
{
    NSArray * arr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"个人信息";
    _dataArr = [[NSMutableArray alloc]init];
    [self createTabView];
    [self createShaowView];
    [self creatNavItem];
}

-(void)creatNavItem{
    UIImage *image = [UIImage imageNamed:@"back1"];
    if (IsIOS7) {
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStyleBordered target:self action:@selector(backtolistentest)];
    self.navigationItem.leftBarButtonItem = backItem;
}


-(void)backtolistentest{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)createTabView{
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped
                  ];
    _tableView.delegate = self;
    
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * str = @"PersonCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell ==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        
        if (indexPath.section ==2) {
            cell.textLabel.text = @"修改密码";
            [self changeSize:indexPath];
            
        }else if (indexPath.section ==1){
            
            cell.textLabel.text = @"性别";
            [self changeSize:indexPath];
            
            
            NSString *module = @"user";
            NSString *interface = @"userinfo";
            
            NSString *timeString = [GetTime getTime];
            NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
            NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
            
            NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid};
            
            //POST请求
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
                //
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            
                NSDictionary * info =[dic objectForKey:@"info"];
                [self createLabelWithFrame:CGRectMake(120 * SCREEN_WIDTH/375, 10* SCREEN_HEIGHT/667, 200 * SCREEN_WIDTH/375,55 *SCREEN_HEIGHT/667) andtitle:[info objectForKey:@"sex"] color:[UIColor lightGrayColor] andIndexPath:cell];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];

            

            
        }else if(indexPath.section ==0){
            
            int b = 70 * SCREEN_HEIGHT/667;
            _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15,20 *SCREEN_HEIGHT/667,b, b)];
            float c = b/2;
            _imageView.layer.cornerRadius = c;
            
            NSURL *headurl = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] valueForKey:USERHEAD_REMBER]];
            NSData * data =[NSData dataWithContentsOfURL:headurl];
            _imageView.image=[UIImage imageNamed:@"portrait"];
            _imageView.image=[UIImage imageWithData:data];
            [_imageView setImageWithURL:headurl placeholderImage:[UIImage imageNamed:@"portrait"]];
            _imageView.clipsToBounds=YES;
            _imageView.layer.borderColor=[UIColor lightGrayColor].CGColor;
            _imageView.layer.borderWidth=2;
            [cell.contentView addSubview:_imageView];
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(25 + 70 *SCREEN_HEIGHT/667, 30*SCREEN_HEIGHT/667, 170*SCREEN_WIDTH/375, 50*SCREEN_HEIGHT/667)];
            label.font = [UIFont systemFontOfSize:16];
            label.text = [NSString stringWithFormat:@"%@",[UserMessage sharedUserMessage].userId];
            if (SCREEN_HEIGHT ==480) {
                label.font = [UIFont systemFontOfSize:14];
            }else if (SCREEN_HEIGHT ==567){
                
                label.font = [UIFont systemFontOfSize:15];
            }
            
            [cell.contentView addSubview:label];
            
            [self createLabelWithFrame:CGRectMake(25 + 70 * SCREEN_HEIGHT/667 + 170 * SCREEN_WIDTH/375 , 30 * SCREEN_HEIGHT/667, 80 * SCREEN_WIDTH/375, 50 * SCREEN_HEIGHT/667) andtitle:@"修改头像" color:[UIColor greenColor] andIndexPath:cell];
        }
        
        
    }
    
    return cell;
    
    
}

#pragma mark 定义cell上的Label
-(void)createLabelWithFrame:(CGRect)frame andtitle:(NSString *)title color:(UIColor *)color andIndexPath:(UITableViewCell *)cell{
    
    UILabel * label = [[UILabel alloc]initWithFrame:frame];
    
    label.text = title;
    label.font =[UIFont systemFontOfSize:14];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = color;
    [cell.contentView addSubview:label];
    
    
}






#pragma mark cell的版本大小在不同设备上
-(void)changeSize:(NSIndexPath *)indexPath{
    
    
    UITableViewCell * cell = [_tableView cellForRowAtIndexPath:indexPath];
    
    cell.textLabel.font = [UIFont systemFontOfSize:18];
    
    if (SCREEN_HEIGHT ==480) {
        cell.textLabel.font = [UIFont systemFontOfSize:14];
    }else if (SCREEN_HEIGHT ==567){
        cell.textLabel.font = [UIFont systemFontOfSize:16];
    }
    
    
    
    
}




-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section ==0) {
        UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
        
        
        [actionSheet showInView:self.view];
    }else if (indexPath.section ==1){
        
        
        _shaowView.hidden = NO;
        
        
    }else{
        
        ChangePassWordVC * pass = [[ChangePassWordVC alloc]init];
        
        
        [self.navigationController pushViewController:pass animated:YES];
        
    }
    
    
    
    
    
}


-(void)createShaowView{
    //阴影的大view
    _shaowView= [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _shaowView.hidden = YES;
    _shaowView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    
    
    UIWindow * keyWindow = [[UIApplication sharedApplication]keyWindow];
    
    [keyWindow addSubview:_shaowView];
    //白色的view
    UIView * showView = [[UIView alloc]initWithFrame:CGRectMake(15, 240 * SCREEN_HEIGHT/667, SCREEN_WIDTH -30, 200 *SCREEN_HEIGHT/667)];
    
    showView.layer.cornerRadius = 6;
    showView.backgroundColor = [UIColor whiteColor];
    
    [_shaowView addSubview:showView];
    
    
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(30 * SCREEN_WIDTH/375,0 , 50 *SCREEN_HEIGHT/667, 200 * SCREEN_HEIGHT/667/4)];
    
    label.text = @"性别";
    
    [showView addSubview:label];
    
    arr = @[@"男",@"女",@"保密"];
    for (int i = 0;  i <3; i++) {
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(30 * SCREEN_WIDTH/375,200 *SCREEN_HEIGHT/667/4 *(i+1)-1, showView.frame.size.width -60 *SCREEN_WIDTH/375, 200 *SCREEN_HEIGHT/667/4)];
        
        view.tag =1000 +i;
        if (i >0) {
            
            
            UIView * view2 = [[UIView alloc]initWithFrame:CGRectMake(30 * SCREEN_WIDTH/375,200 *SCREEN_HEIGHT/667/4 *(i+1), showView.frame.size.width -60 *SCREEN_WIDTH/375, 1)];
            view2.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
            [showView addSubview:view2];
        }
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0,0,  50 *SCREEN_HEIGHT/667, 200 * SCREEN_HEIGHT/667/4)];
        //        label.backgroundColor = [UIColor yellowColor];
        label.text = arr[i];
        
        label.font = [UIFont systemFontOfSize:15];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapShowImage:)];
        
        [view addGestureRecognizer:tap];
        
        
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(showView.frame.size.width -60 *SCREEN_WIDTH/375 -15, 25, 10, 10)];
        
        
        imageView.hidden =YES;
        imageView.layer.cornerRadius = 5;
        imageView.backgroundColor = [UIColor greenColor];
        [view addSubview:imageView];
        
        imageView.tag = 888 + i;
        [_dataArr addObject:imageView];
        
        [view addSubview:label];
        
        
        
        //view.backgroundColor =[UIColor redColor];
        [showView addSubview:view];
    }
    
    
    
}




-(void)tapShowImage:(UIGestureRecognizer *)tap{
    
    //    NSLog(@"%ld",(long)tap.view.tag);
    UIImageView * imagView =(UIImageView *) [_shaowView viewWithTag:tap.view.tag - 1000 + 888];
    for (UIImageView * imageName in _dataArr) {
        if ([imagView isEqual:imageName]) {
            imagView.hidden = NO;
        }else{
            imageName.hidden = YES;
        }
        
    }
     NSString * sex;
    NSUserDefaults *user =[NSUserDefaults standardUserDefaults];
    if (tap.view.tag==1000) {
        [user setObject:@"男" forKey:@"sex"];
        sex=@"男";
        [self createTabView];
    }else if (tap.view.tag==1001){
        [user setObject:@"女" forKey:@"sex"];
        sex=@"女";
        [self createTabView];
    }else{
        [user setObject:@"保密" forKey:@"sex"];
        sex=@"保密";
        [self createTabView];
    }
    [user synchronize];
    
   
    
    
    NSString *module = @"user";
    NSString *interface = @"updateuserinfo";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid,@"sex":sex};
    
    //POST请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

    
    _shaowView.hidden =YES;
    
    
    
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex !=2) {
        
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        
        picker.delegate =self;
        picker.allowsEditing = YES;
        
        if (buttonIndex ==0) {
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                
                [self presentViewController:picker animated:YES completion:nil];
            }else{
                
            }
            
            
            
        }else if (buttonIndex ==1){
            
            
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                
                
                [self presentViewController:picker animated:YES completion:nil];
                
                
            }else{
                
            }
            
            
        }
    }
    
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    
    
    
    NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
        _imageView.image = image;
        NSData * picData = UIImageJPEGRepresentation(image, 0.5);
        
        /***********图片上传服务器********/
        
        
        
        
        NSString *module = @"user";
        NSString *interface = @"updateavatar";

        NSString *timeString = [GetTime getTime];
        NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
        NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];

        
        
        NSDictionary *parameter = @{@"time":timeString,@"username":[UserMessage sharedUserMessage].userId,@"mid":[UserMessage sharedUserMessage].userMid,@"headimg":picData};
        
        

        //POST请求
                AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
                manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:urlString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            [formData appendPartWithFormData:picData name:@"headimg"];
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSString * str =[dic objectForKey:@"info"];
            
            [[NSUserDefaults standardUserDefaults] setValue:str forKey:USERHEAD_REMBER];
            NSLog(@"%@------------00--00--0",dic);
            //            NSLog(@"%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        }];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section ==0) {
        return 0.01;
    }
    return 30;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section ==0) {
        return 110.0 * SCREEN_HEIGHT/667;
    }
    
    return 70* SCREEN_HEIGHT/667;
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    if (section ==1) {
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        view.backgroundColor = [UIColor whiteColor];
        return view;
    }
    UIView * view = [[UIView alloc]init];
    
    return view;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}






@end
